<template>
  <div>
    <a-card>
      <!-- 搜索部分 -->
      <a-row type="flex" justify="space-between" style="margin-bottom: 20px">
        <a-col>
          <a-input-search
            style="width: 180px; margin-right: 20px"
            v-model:value="searchInfo.phonenumber"
            placeholder="客户手机号"
            @search="getList"
          />
          <a-select
            v-model:value="searchInfo.followStatus"
            allowClear
            style="width: 180px; margin-right: 20px"
            placeholder="跟进状态"
            @change="getList"
          >
            <a-select-option :value="1">未跟进</a-select-option>
            <a-select-option :value="2">已跟进</a-select-option>
            <a-select-option :value="3">已转化</a-select-option>
          </a-select>
          <a-select
            v-model:value="searchInfo.score"
            allowClear
            style="width: 180px; margin-right: 20px"
            placeholder="意向打分"
            @change="getList"
          >
            <a-select-option v-for="item in 5" :key="item" :value="item">
              <a-rate :value="item" disabled />
            </a-select-option>
            <a-select-option :value="0">
              <a-rate :value="0" disabled />
            </a-select-option>
          </a-select>
        </a-col>
        <a-col>
          <a-button type="primary" @click="confirmExport">导出</a-button>
        </a-col>
      </a-row>
      <!-- 列表部分 -->
      <a-table
        :columns="allStoreCol"
        :data-source="state.dataSource"
        :pagination="false"
        :loading="state.loading"
        rowKey="userId"
        @change="tableChange"
      >
        <template #customTitle>
          <div>
            创建店铺数量
            <a-tooltip placement="top">
              <template #title>
                <span>当前属于该账号的店铺数量</span>
              </template>
              <info-circle-outlined />
            </a-tooltip>
          </div>
        </template>
        <template #allShopNumTitle>
          <div>
            全部店铺数量
            <a-tooltip placement="top">
              <template #title>
                <span>当前该账号可管理的店铺数量</span>
              </template>
              <info-circle-outlined />
            </a-tooltip>
          </div>
        </template>
        <template #score="{ record }">
          <a-rate :value="record.score" disabled />
        </template>
        <!-- 操作 -->
        <template #handler="{ record }">
          <a @click="getFollowStatus(record)">跟进记录</a>
          <span style="color: #1890ff; margin: 0 6px">|</span>
          <a @click="getStore(record)">查看店铺</a>
        </template>
      </a-table>
      <!-- 分页部分 -->
      <a-row style="margin-top: 20px" type="flex" justify="end">
        <a-pagination
          show-quick-jumper
          showSizeChanger
          v-model:pageSize="pagination.pageSize"
          v-model:current="pagination.pageNum"
          :total="pagination.total"
          :showTotal="() => `共 ${pagination.total} 条数据`"
          @change="getList"
          @showSizeChange="getList"
        />
      </a-row>
      <!-- 跟进记录弹出框 -->
      <follow-log
        v-model:visible="showLogInfo"
        :current="currentLog"
        @close-log="resetLogInfo"
        @getList="getList"
      ></follow-log>
      <!-- 查看店铺弹出框 -->
      <a-drawer v-bind="showStoreDrawer" @close="closeStoreInfo">
        <!-- 当前账户管理的店铺 -->
        <div>
          <div class="store-detail_table-title">
            管理的店铺：{{ storeManage.dataSource.length }}个
          </div>
          <div>
            <a-table
              class="store-detail_table"
              :columns="storeManageCol"
              :data-source="storeManage.dataSource"
              :loading="storeManage.loading"
              :pagination="false"
              rowKey="shopId"
              @change="storeManageChange"
            >
              <template #shopName="{ record }">
                <div style="padding-left: 8px">{{ record.shopName }}</div>
              </template>
              <template #shopType="{ record }">
                <a-badge
                  :color="record.shopType === '试用' ? '#ccc' : '#76db93'"
                  :text="record.shopType"
                ></a-badge>
              </template>
            </a-table>
          </div>
        </div>
        <div style="border-bottom: 1px dashed #ccc; margin: 20px 0"></div>
        <!-- 作为员工的店铺 -->
        <div>
          <div class="store-detail_table-title">
            作为员工的店铺：{{ staffStore.dataSource.length }}个
          </div>
          <div>
            <a-table
              class="store-detail_table"
              rowKey="shopId"
              :columns="storeManageCol"
              :data-source="staffStore.dataSource"
              :loading="staffStore.loading"
              :pagination="false"
              @change="createStoreChange"
            >
              <template #shopName="{ record }">
                <div style="padding-left: 8px">{{ record.shopName }}</div>
              </template>
              <template #shopType="{ record }">
                <a-badge
                  :color="record.shopType === '试用' ? '#ccc' : '#76db93'"
                  :text="record.shopType"
                ></a-badge>
              </template>
            </a-table>
          </div>
        </div>
      </a-drawer>
    </a-card>
  </div>
</template>

<script>
import { Rate } from 'ant-design-vue';
import { defineComponent, reactive, ref } from 'vue';
import {
  apiGetClientAccountList,
  apiGetCreateStoreList,
  apiGetManageStoreList,
  apiExportClientAccount,
} from '@/api/clientManage/account';
import { parseTime, downloadFile } from '@/utils';
import FollowLog from './components/followLog';
import { InfoCircleOutlined } from '@ant-design/icons-vue';
// 商户列表列
const allStoreCol = [
  {
    title: '手机号',
    dataIndex: 'phonenumber',
  },
  {
    title: '跟进状态',
    dataIndex: 'followStatusVal',
    sorter: true,
    sortDirections: ['descend', 'ascend'],
  },
  {
    title: '意向打分',
    dataIndex: 'score',
    sorter: true,
    sortDirections: ['descend', 'ascend'],
    slots: {
      customRender: 'score',
    },
  },
  {
    dataIndex: 'shopNum',
    slots: {
      title: 'customTitle',
    },
    sortDirections: ['descend', 'ascend'],
    sorter: true,
  },
  {
    dataIndex: 'allShopNum',
    sorter: true,
    sortDirections: ['descend', 'ascend'],
    slots: {
      title: 'allShopNumTitle',
    },
  },
  {
    title: '注册时间',
    dataIndex: 'createTime',
    sorter: true,
    sortDirections: ['descend', 'ascend'],
  },
  {
    title: '最后登录时间',
    dataIndex: 'loginDate',
    sorter: true,
    sortDirections: ['descend', 'ascend'],
  },
  {
    title: '操作',
    dataIndex: 'handler',
    slots: {
      customRender: 'handler',
    },
  },
];

// 商铺列表列
const storeManageCol = [
  {
    title: '店铺ID',
    dataIndex: 'shopId',
  },
  {
    title: '店铺名称',
    dataIndex: 'shopName',
    slots: {
      customRender: 'shopName',
    },
  },
  {
    title: '店铺状态',
    dataIndex: 'shopStatus',
    sorter: true,
    sortDirections: ['descend', 'ascend'],
  },
  {
    title: '当前版本',
    dataIndex: 'shopType',
    sortDirections: ['descend', 'ascend'],
    slots: {
      customRender: 'shopType',
    },
    sorter: true,
  },
  {
    title: '到期时间',
    dataIndex: 'expirationTime',
    sorter: true,
    sortDirections: ['descend', 'ascend'],
  },
];

const transStoreList = list => {
  // const statusMap = {
  //   0: '已打烊',
  //   1: '营业中',
  // };
  const shopTypeMap = {
    standard: '标准',
    professional: '专业',
    advanced: '高级',
    trial: '试用',
  };
  return list.map(item => {
    item.shopStatus = item.shopStatusVal;
    item.shopType = shopTypeMap[item.shopType];
    item.expirationTime = item.expireTimes;
    return item;
  });
};

export default defineComponent({
  name: 'AccountManage',
  setup() {
    // 搜索内容
    const searchInfo = reactive({
      phonenumber: '', // 客户手机号
      score: undefined, // 意向打分
      followStatus: undefined, // 跟进状态 1未跟进 2已跟进 3已转化
    });

    // 分页数据
    const pagination = reactive({ pageSize: 10, pageNum: 1, total: 0 });

    // 存放列表数据
    const state = reactive({ dataSource: [], loading: false });

    /**
     * 获取列表
     **/
    const getList = async (params = {}) => {
      if (state.loading) return;
      try {
        state.loading = true;
        const { pageInfo } = await apiGetClientAccountList({
          pageNum: pagination.pageNum,
          pageSize: pagination.pageSize,
          phonenumber: searchInfo.phonenumber,
          followStatus: searchInfo.followStatus,
          score: searchInfo.score,
          ...params,
        });
        state.dataSource = pageInfo.list.map(item => {
          item.loginDate = item.loginDate || '-';
          return item;
        });
        pagination.total = pageInfo.total;
      } finally {
        state.loading = false;
      }
    };
    getList();

    /**
     * 导出账号文件
     **/
    let exportQuery = {};
    const confirmExport = async () => {
      await apiExportClientAccount({
        phonenumber: searchInfo.phonenumber,
        followStatus: searchInfo.followStatus,
        score: searchInfo.score,
        ...exportQuery,
      }).then(res => {
        downloadFile(res, {
          fileName: `账号管理${parseTime(new Date(), '{y}年{m}月{d}日{h}：{m}：{s}')}`,
        });
      });
    };

    /**
     * 获取排序
     **/
    const tableChange = (pag, filters, sorter) => {
      // followStatusVal实际不存在于数据库中，实际存储为followStatus
      const sortCol = sorter.field === 'followStatusVal' ? 'followStatus' : sorter.field;
      const sortOrder = sorter.order === 'descend' ? 0 : 1;
      exportQuery = { sortCol, sortOrder };
      getList(exportQuery);
    };

    /**
     * 跟进记录弹出框
     **/
    const currentLog = ref({});
    const showLogInfo = ref(false);
    const getFollowStatus = row => {
      showLogInfo.value = true;
      currentLog.value = row;
    };

    /**
     * 关闭记录弹出框
     **/
    const resetLogInfo = () => {
      showLogInfo.value = false;
      currentLog.value = {};
    };

    /**
     * 查看店铺弹出框
     **/
    const currentStore = ref({});
    const showStoreDrawer = reactive({
      visible: false,
      title: '查看店铺',
      width: 800,
      placement: 'right',
    });
    const getStore = record => {
      showStoreDrawer.visible = true;
      currentStore.value = record;
      confirmGetManageStore();
      confirmGetCreateStore();
    };

    /**
     * 获取创建商铺列表
     **/
    const staffStore = reactive({
      dataSource: [],
      loading: false,
    });
    const confirmGetCreateStore = async (query = {}) => {
      if (staffStore.loading) return;
      const { userId } = currentStore.value;
      try {
        staffStore.loading = true;
        const { dataInfo } = await apiGetManageStoreList({
          userId,
          ...query,
        });
        staffStore.dataSource = transStoreList(dataInfo);
      } finally {
        staffStore.loading = false;
      }
    };

    /**
     * 更改创建商铺排序
     **/
    const createStoreChange = (pag, filters, sorter) => {
      const sortOrder = sorter.order === 'descend' ? 0 : 1;
      const querySort = { sortCol: sorter.field, sortOrder };
      confirmGetCreateStore(querySort);
    };

    /**
     * 获取管理商铺列表
     **/
    const storeManage = reactive({
      loading: false,
      dataSource: [],
    });
    const confirmGetManageStore = async (query = {}) => {
      if (storeManage.loading) return;
      try {
        const { userId } = currentStore.value;
        storeManage.loading = true;
        const { dataInfo } = await apiGetCreateStoreList({
          userId,
          ...query,
        });
        storeManage.dataSource = transStoreList(dataInfo);
      } finally {
        storeManage.loading = false;
      }
    };

    /**
     * 更改管理商铺排序
     **/
    const storeManageChange = (pag, filters, sorter) => {
      const sortOrder = sorter.order === 'descend' ? 0 : 1;
      const querySort = { sortCol: sorter.field, sortOrder };
      confirmGetManageStore(querySort);
    };

    /**
     * 关闭店铺查看弹出框
     **/
    const closeStoreInfo = () => {
      showStoreDrawer.visible = false;
      currentStore.value = {};
      storeManage.dataSource = [];
      staffStore.dataSource = [];
    };

    return {
      searchInfo,
      allStoreCol,
      storeManageCol,
      state,
      pagination,
      tableChange,
      showLogInfo,
      getFollowStatus,
      resetLogInfo,
      getList,
      getStore,
      showStoreDrawer,
      closeStoreInfo,
      storeManage,
      storeManageChange,
      createStoreChange,
      currentStore,
      currentLog,
      staffStore,
      confirmExport,
    };
  },
  components: {
    aRate: Rate,
    FollowLog,
    InfoCircleOutlined,
  },
});
</script>
<style lang="less">
.store-detail_table {
  .ant-table-thead > tr > th .ant-table-column-sorter .ant-table-column-sorter-inner {
    margin-left: 4px !important;
  }
}
.store-detail_table-title {
  position: relative;
  margin-bottom: 20px;
  padding-left: 12px;
  font-weight: 700;
  font-size: 16px;
  &::before {
    position: absolute;
    top: 6px;
    left: 0;
    display: block;
    width: 3px;
    height: 14px;
    background-color: #1890ff;
    border-radius: 2px;
    content: '';
  }
}
</style>
